class SongsController < ApplicationController
  before_filter :require_admin,   :only => [:new,   :create,  :edit,    :update,  :destroy]
  before_filter :find_song,       :only => [:show,  :edit,    :update,  :destroy]
  before_filter :find_list_items, :only => [:show,  :new,     :update,  :create,  :edit]  

  def index
    @albumless_songs = Song.find(:all, :conditions => ['album_id IS ?', nil], :order => 'album_id, name ASC')
    @albums = Album.find(:all, :order => 'name ASC')
  end

  def show
    @comment = Comment.new
    respond_to do |song|
      song.html   {}
      song.xml    {render :xml => @song.xml(song_url(@song), home_url)}
    end
  end

  def new
    @song = Song.new
  end

  def create
    @song = Song.new(params[:song])
    @song.save!
    flash[:update] = 'The song has been added'
    redirect_to song_url(@song)
  rescue ActiveRecord::RecordInvalid
    flash[:error] = "Oops, that didn't work, see below."
    render :action => 'new'
  end

  def edit
  end

  def update
    @song.update_attributes!(params[:song])
    flash[:update] = 'The song information has been updated.'
    redirect_to song_url(@song)
  rescue ActiveRecord::RecordInvalid
    flash[:error] = "Oops, that didn't work, see below."
    render :action => 'edit'
  end

  def destroy
    @song.destroy
    flash[:update] = 'The song has been deleted.'
    redirect_to songs_url
  end

protected
  def require_login
    unless logged_in?
      flash[:error] = 'You must be logged in to do that'
      redirect_to login_url
    end
  end
  def require_admin
    if logged_in?
      unless current_user.is_admin?
        flash[:error] = "Must be an administrator to do that, sorry."
        redirect_back_or_default('/')
      end
    else
      flash[:error] = 'You must be logged in to do that'
      redirect_to login_url
    end
  end
  def find_song
    @song = Song.find params[:id]
  end
  def find_list_items
    @shows    = Show.find     :all, :order => 'created_at desc'
    @albums   = Album.find    :all, :order => 'created_at desc'
    @artwork  = Artwork.find  :all, :order => 'created_at desc', :conditions => ["thumbnail IS ?", nil]
    @photos   = Photo.find    :all, :order => 'created_at desc', :conditions => ["thumbnail IS ?", nil]
    @videos   = Video.find    :all, :order => 'created_at desc'
    @users    = User.find     :all, :order => 'created_at desc'
  end
end
